<script setup lang="ts">
import { ref, onBeforeMount, onMounted } from "vue";
import {
  getAllInquiryProdectsInfo,
  saveInquiryProductsInfo
} from "@/api/inquiryApi";
import { useUserStoreHook } from "@/store/modules/user";
import { useRoute, useRouter } from "vue-router";
import { productStore } from "@/store/modules/products";
import { getDictByCode } from "@/api/dictApi";
const user = useUserStoreHook();
const productStore1 = productStore();
const route = useRoute();
const router = useRouter();
//跳转到添加产品
function toAddProduct() {
  router.push({
    path: "/inquiry/addProduct"
  });
}
onMounted(() => {
  fuzhi();
  dict();
});
onBeforeMount(() => {
  if (route.query.prodects) {
    productStore1.productList = [
      ...productStore1.productList,
      ...JSON.parse(route.query.prodects as string)
    ].filter(
      (item, index, self) =>
        index ===
        self.findIndex(
          t => t.productId === item.productId // 假设每个对象有一个唯一的 `id` 属性
        )
    );
    prodects.value = productStore1.productList;
    prodects.value.map(item => mapData(item, mappingRules));
    prodects.value.forEach(value => {
      value.demand = 1;
    });
  }
  if (route.query.id) {
    productStore1.inquiryInfo.sellerName = route.query.saleName as string;
    productStore1.inquiryInfo.sellerId = route.query.saleId as string;
    productStore1.inquiryInfo.customerContactPeople = route.query
      .contacts as string;
    productStore1.inquiryInfo.customerContactNumber = route.query
      .mobile as string;
    productStore1.inquiryInfo.customerName = route.query.contacts as string;
    productStore1.inquiryInfo.status = route.query.status as string;
    fuzhi();
    getInquiryProdectsInfo(route.query.id);
  }
});

function fuzhi() {
  InquiryInfo.value.customerContactPeople =
    productStore1.inquiryInfo.customerContactPeople;
  InquiryInfo.value.customerContactNumber =
    productStore1.inquiryInfo.customerContactNumber;
  InquiryInfo.value.customerName = productStore1.inquiryInfo.customerName;
  InquiryInfo.value.status = productStore1.inquiryInfo.status;
}
async function getInquiryProdectsInfo(id) {
  let res = await getAllInquiryProdectsInfo(id);
  if (res.code === 200) {
    productStore1.clear();
    const mappedData = res.data.customerInquiryDetails.map(item =>
      mapData(item, mappingRules)
    );
    productStore1.productList.push(...mappedData);
    prodects.value = productStore1.productList;
    prodects.value.forEach(value => {
      value.demand = 1;
    });
  }
}
//产品表格
const prodects = ref();

// 定义映射规则
const mappingRules = {
  // 目标属性: 源属性
  productName: "name",
  productCover: "picurl",
  productId: "pid",
  productModel: "model"
};
// 通用映射函数
function mapData(source, rules) {
  return Object.keys(rules).reduce((acc, targetKey) => {
    const sourceKey = rules[targetKey];
    acc[targetKey] = source[sourceKey];
    return acc;
  }, {});
}
//询价单信息
const InquiryInfo = ref({
  categoryId: "",
  companyId: 0,
  customerContactNumber: "",
  customerContactPeople: "",
  customerName: "",
  extra: "",
  inquiryDate: "",
  needNum: 0,
  status: "",
  isDo: "",
  brand: "",
  model: "",
  erpProductInquirySheetProducts: []
});
//下拉菜单列表
async function dict() {
  //分类
  let res2 = await getDictByCode(15);
  categoryOptions.value = res2.data.subDict;
  //型号
  let res3 = await getDictByCode(16);
  modelOptions.value = res3.data.subDict;
  //品牌
  let res4 = await getDictByCode(14);
  brandOptions.value = res4.data.subDict;
}
const categoryOptions = ref();
const modelOptions = ref();
const brandOptions = ref();
//保存 取消
//保存 跳转到创建询价单页面
function toCustomerInquiry() {
  if (!formRef.value) return;
  formRef.value.validate(async valid => {
    if (valid) {
      InquiryInfo.value.erpProductInquirySheetProducts = prodects.value;
      let res = await saveInquiryProductsInfo(InquiryInfo.value);
      if (res.code == 200) {
        router.push({
          path: "/inquiry/CustomerInquiry"
        });
        productStore1.reset();
        productStore1.clear();
      }
    }
  });
}
function cancel() {
  router.push({ path: "/inquiry/CustomerInquiry" });
  productStore1.reset();
  productStore1.clear();
}

//删除商品
function deleteRow(index, row) {
  prodects.value.splice(index, 1);
}

//表单校验对象
const formRef = ref();
</script>

<template>
  <div>
    <!-- 报价信息 -->
    <el-card style="margin-top: 30px; height: 300px">
      <template #header>
        <div class="card-header">
          <span>报价信息</span>
        </div>
      </template>
      <div>
        <el-form
          ref="formRef"
          label-position="left"
          :model="InquiryInfo"
          :inline="true"
          class="demo-form-inline"
          style="margin: 20px auto"
        >
          <el-form-item label="询价客户：" prop="customerContactPeople">
            <el-input
              v-model="InquiryInfo.customerContactPeople"
              disabled
              clearable
            />
          </el-form-item>
          <el-form-item
            label="询价日期："
            :required="true"
            prop="inquiryDate"
            label-width="100"
          >
            <el-date-picker
              v-model="InquiryInfo.inquiryDate"
              type="date"
              placeholder="下拉选择时间"
            />
          </el-form-item>
          <br />

          <el-form-item label="机器品牌：" :required="true" prop="brand">
            <el-select
              v-model="InquiryInfo.brand"
              placeholder="下拉选择"
              clearable
              :required="true"
            >
              <el-option
                v-for="item in brandOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="机器型号：" :required="true" prop="model">
            <el-select
              v-model="InquiryInfo.model"
              placeholder="下拉选择"
              clearable
              allow-create
            >
              <el-option
                v-for="item in modelOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <br />
          <el-form-item label="公司是否做过" :required="true" prop="isDo">
            <el-select
              v-model="InquiryInfo.isDo"
              placeholder="下拉选择"
              clearable
            >
              <el-option label="是" value="1" />
              <el-option label="否" value="2" />
              <el-option label="未知" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="产品类型" :required="true" prop="categoryId">
            <el-select
              v-model="InquiryInfo.categoryId"
              placeholder="下拉选择"
              style="width: 240px"
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 产品信息 -->
    <el-card style="margin-top: 30px">
      <template #header>
        <div class="card-header">
          <span>产品信息</span>
        </div>
      </template>
      <div>
        <div style="margin-left: 88px">
          <el-table :data="prodects" border style="width: 87%" height="300">
            <el-table-column
              prop="coverImage"
              label="产品图片"
              width="193"
              align="center"
            >
              <template v-slot="{ row }">
                <el-image
                  style="width: 50px; height: 50px"
                  :src="row.coverImage"
                  :fit="'fill'"
                  align="center"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="productName"
              label="产品名称"
              width="190"
              header-align="center"
              align="center"
            />
            <el-table-column
              prop="productModel"
              label="产品型号"
              width="180"
              header-align="center"
              align="center"
            />
            <el-table-column
              prop="demand"
              label="需求数量"
              width="180"
              header-align="center"
              align="center"
            >
              <template v-slot="{ row }">
                <el-input-number v-model="row.demand" :min="1" />
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              min-width="120"
              width="240"
              header-align="center"
              align="center"
            >
              <template v-slot="scope">
                <el-button link type="primary" size="small">历史报价</el-button>
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click.prevent="deleteRow(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button
          type="primary"
          plain
          style="width: 100%"
          @click="toAddProduct"
          >添加产品</el-button
        >
      </template>
    </el-card>

    <el-card style="margin-top: 30px">
      <el-button
        type="primary"
        style="width: 40%; margin-left: 50px"
        @click="toCustomerInquiry"
        >保存</el-button
      >
      <el-button type="primary" style="width: 40%" @click="cancel"
        >取消</el-button
      >
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
